<template>
  <div class="show-list">
    <div class="contacts-left">
      <TjTree
        v-model:expanded="expanded"
        v-model:actived="actived"
        :data="departmentDatas"
        :keys="{ label: 'categoryName', value: 'categoryId', children: 'childList' }"
        :expand-on-click-node="true"
        activable
        hover
        transition
        @click="onClick"
        @active="onActive"
        @change="onChange"
        @expand="onExpand"
      />
    </div>
    <div v-if="contactsChildList.length !== 0" class="contacts-child">
      <label v-if="maxCount * 1 !== 1" class="checkbox-labels">
        <TjCheckbox
          :checked="allChecked"
          :indeterminate="indeterminate"
          :disabled="allDisabled"
          @change="clickAllHandler($event)"
        />
        <span>全选 </span>
      </label>
      <div class="child-box">
        <template v-for="(item, index) in contactsChildList" :key="item.id">
          <div class="child-li">
            <TjCheckbox
              :checked="item.checked"
              :disabled="item.disabled"
              class="checked-box"
              @change="clickHandler($event, item, index)"
            >
              <div class="boxs">
                <img v-if="item.avatar" class="avatar" :src="item.avatar" alt="" />
                <img v-else class="avatar" src="@/assets/img/oa-img-default.png" alt="" />
                <TjPopup
                  class="placement top center"
                  :disabled="item.userName.length > 12 ? false : true"
                  :content="item.userName"
                  placement="top"
                  :overlay-style="{ maxWidth: '215px' }"
                  show-arrow
                  destroy-on-close
                >
                  <div class="user-name">{{ item.userName }}</div>
                </TjPopup>
              </div>
            </TjCheckbox>
          </div>
        </template>
      </div>
    </div>
    <template v-else>
      <div v-if="expanded.length === 0" class="no-child">
        <img src="../../../../assets/img/default_add_img_zujian@2x.png" alt="" />
        <div class="span">请先选择校区</div>
      </div>
      <div v-else class="no-child">
        <img src="../../../../assets/img/default_search_img_people@2x.png" alt="" />
        <div class="span">暂无成员</div>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  name: 'ShowList'
};
</script>
<script setup>
import store from '@/store';
import { TjTree, TjCheckbox, TjPopup } from 'tj-design-vue';
import { computed, defineProps, ref, inject, nextTick, onMounted, watch, defineExpose } from 'vue';
const props = defineProps({
  data: {
    type: Object
  },
  height: {
    type: Number
  },
  tabActive: {
    type: String // 部门还是角色
  }
});
let domHeight = ref(0); // 左侧组织dom高度
let domPeopleHeight = ref(0); // 右侧人dom高度
let departmentDatas = ref([]); // 组织结构数据
const contactsChildList = ref([]); // 选中当前组织下的人
const allChecked = computed(() => contactsChildList.value.length === allCheckedTrue.value.length); // 是否选中
const indeterminate = ref(false); // 半全选状态
// 选中列表
const selectList = inject('selectList');
function getChecked(type) {
  console.log('getChecked', type);
  if (type === 'allPeople' || type === 'checkAllPeople') {
    deleteAll(); // 全部删除
  } else {
    mateSelectId(type); // 单个删除 匹配选中id
  }
}
// 去除全部人
const deleteAll = () => {
  allCheckedTrue.value = [];
  contactsChildList.value.forEach(ite => {
    ite.checked = false;
    ite.disabled = false;
  });
};
defineExpose({
  getChecked
});
onMounted(() => {
  setTimeout(() => {
    departmentDatas.value = store.state.user.departmentDatas;
    domHeight.value = store.state.user.contactsHeight + 'px';
    domPeopleHeight.value = store.state.user.contactsHeight - 38 + 'px';
  });
  const storage = JSON.parse(sessionStorage.getItem('tabStorageClass')); // 存贮展开值
  // console.log(storage);
  if (store.state.user.departmentDatas.length === 1) {
    if (storage) {
      expanded.value = storage.two;
      actived.value = storage.one;
      contactsChildList.value = JSON.parse(sessionStorage.getItem('classPeople'));
    } else {
      processLists(store.state.user.departmentDatas);
      actived.value = [expanded.value[expanded.value.length - 1]]; // 选中节点
    }
    mateSelectId(); // 处理选中id匹配状态
  } else {
    // 关联多个校区， 关闭所有层级
    if (storage) {
      expanded.value = storage.two;
      actived.value = storage.one;
      contactsChildList.value = JSON.parse(sessionStorage.getItem('classPeople'));
      mateSelectId(); // 处理选中id匹配状态
    } else {
      // currentItem.value = [];
    }
  }
});
// 枚举数据结构
function processLists(items) {
  if (items[0].childList) {
    expanded.value.push(items[0].categoryId); // 展开节点
    // console.log(expanded.value);
    // 没有关联校区, 默认显示第一组织的最里层
    contactsChildList.value = items[0].listPeople;
    if (items[0].childList.length > 0) processLists(items[0].childList);
  }
}
// 可选择人数
const maxCount = inject('maxCount');
// 是否禁用
const disabled = computed(() => selectList.value.length === maxCount.value * 1);
const mateSelectId = type => {
  console.log(type, '部门');
  contactsChildList.value.forEach(it => {
    it.checked = false;
    it.disabled = disabled.value;
  });
  selectList.value.forEach(item => {
    contactsChildList.value.forEach(it => {
      if (it.userId === item.userId) {
        it.disabled = false;
        it.checked = true;
      }
    });
  });
  allCheckedState();
};
const addOrDelSelectHandler = inject('addOrDelSelectHandler'); // 添加或者删除选中人员
const getPeople = inject('getPeople'); // 添加或者删除选中人员 触发子组件事件选中对应的人
// 点击多选框
const clickHandler = (e, item, index) => {
  contactsChildList.value[index].username = contactsChildList.value[index].userName;
  addOrDelSelectHandler(e, [contactsChildList.value[index]], 'userId');
  getPeople();
  contactsChildList.value[index].checked = e;
  mateSelectId();
};
// 点击全选框
const clickAllHandler = e => {
  if (e) indeterminate.value = false;
  // console.log(contactsChildList.value.length);
  // console.log(maxCount.value, selectList.value.length);
  if (contactsChildList.value.length >= maxCount.value * 1 - selectList.value.length) {
    console.log(e);
    let list = [];
    contactsChildList.value.forEach((item, index) => {
      if (index < maxCount.value) {
        item.checked = e;
        item.username = item.userName;
        list.push(item);
      } else {
        item.disabled = true;
        indeterminate.value = true;
        allDisabled.value = true;
      }
    });
    addOrDelSelectHandler(e, list, 'userId', e ? 'checkAllPeople' : null);
  } else {
    console.log(2222);
    contactsChildList.value.forEach((item, index) => {
      item.checked = e;
      item.username = item.userName;
    });
    addOrDelSelectHandler(e, contactsChildList.value, 'userId', e ? 'checkAllPeople' : null);
  }
  allPeople(e);
};
const allPeople = type => {
  if (type) {
    let list = [];
    contactsChildList.value.forEach(item => {
      if (item.checked) list.push(item.checked);
    });
    // console.log(4444, list);
    allCheckedTrue.value = list;
  } else {
    allCheckedTrue.value = [];
  }
};
// 处理选中状态
const allCheckedTrue = ref([]); // 当前选中人集合
const allDisabled = ref(false); // 全选禁用状态
const allCheckedState = () => {
  let list = [];
  let disabledList = [];
  contactsChildList.value.forEach(item => {
    if (item.disabled) disabledList.push(item.disabled);
    if (item.checked) list.push(item.checked);
  });
  if (disabledList.length > 0) allDisabled.value = true;
  if (disabledList.length === 0) allDisabled.value = false;
  allCheckedTrue.value = list;
  if (list.length === 0) {
    indeterminate.value = false;
  } else {
    if (allChecked.value) {
      indeterminate.value = false;
    } else {
      if (allCheckedTrue.value.length !== 0) {
        indeterminate.value = true;
      }
    }
  }
};
const expanded = ref([]); // 展开节点
const actived = ref([]); // 选中节点
// 树结构事件
const onClick = context => {
  // if (expanded.value.length === 1) {
  // store.state.user.departmentDatas.forEach(item => {
  // if (item.categoryId === context.node.data.categoryId) processLists([item]);
  // actived.value = [expanded.value[expanded.value.length - 1]]; // 选中节点
  // });
  // console.log(store.state.user.departmentDatas);
  // }
};
const onChange = (checked, context) => {
  // console.log('onChange:', checked, context);
};
const expandIds = ref([]);
const onExpand = (vals, state) => {
  store.state.user.departmentDatas.forEach(item => {
    // 匹配下categoryId 只看最外层的categoryId 子集不需要处理
    if (item.categoryId === state.node.data.categoryId) {
      if (expanded.value.indexOf(state.node.data.categoryId) !== -1) {
        console.log(1111, '包含');
        // processLists([item]);
        // actived.value = [expanded.value[expanded.value.length - 1]]; // 选中节点
      } else {
        console.log('不包含');
        // actived.value = [];
        expanded.value = [];
      }
    }
  });
  mateSelectId();
};
const onActive = (value, context) => {
  // 选中父级 value=>['1111111111']
  // console.log('onActive', value, context);
  contactsChildList.value = context.node.data.listPeople;
  // console.log(contactsChildList.value);
  sessionStorage.setItem('tabStorageClass', JSON.stringify({ one: value, two: expanded.value })); // 存储角色选中值[two:当前选中角色， one:多个组织的时候有此值]
  // const storage = JSON.parse(sessionStorage.getItem('tabStorageClass')); // 存贮展开值
  sessionStorage.setItem('classPeople', JSON.stringify(contactsChildList.value));
  // console.log(expanded.value);
  mateSelectId(); // 匹配选中id
};
</script>

<style lang="less" scoped>
.show-list {
  display: flex;
  .contacts-left {
    width: 50%;
    height: v-bind('domHeight');
    overflow: auto;
  }
  .child-box {
    overflow: auto;
    height: v-bind('domPeopleHeight');
  }
  // border: 1px solid red;
  .all-checkbox {
    width: 100%;
    height: 38px;
    border-radius: 4px;
    margin: 4px 0;
    &:hover {
      background: #f5f6f7;
    }
  }
  .contacts-child {
    width: 50%;
    .checkbox-labels {
      width: 234px;
      padding: 8px;
      height: 38px;
      display: flex;
      align-items: center;
    }
    .picks-checkboxs {
      cursor: pointer;
      width: 16px;
      height: 16px;
      background: #ffffff;
      border: 1px solid rgba(186, 191, 197, 0.4);
      border-radius: 4px;
      margin-right: 8px;
    }
    .child-li:hover {
      background: #f5f6f7;
    }
    .child-li {
      display: flex;
      align-items: center;
      width: 249px;
      height: 38px;
      padding: 8px;
      // background: #f5f6f7;
      img {
        width: 32px;
        height: 32px;
        border-radius: 4px;
        margin-right: 12px;
      }
      .user-name {
        width: 164px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .no-child {
    margin: auto;
    img {
      margin: 0 auto;
      width: 164px;
      height: 164px;
    }
    .span {
      font-size: 14px;
      font-family: Microsoft YaHei, Microsoft YaHei-400;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.4);
      text-align: center;
      // margin-top: 40px;
    }
  }
}
/deep/ .tj-tree--transition {
  padding: 1px 0 2px 5px !important;
}
/deep/ .tj-tree__item {
  // padding-top: 2px !important;
  padding-bottom: 3px !important;
  // width: 228px;
  // overflow: hidden;
  // white-space: nowrap;
  // text-overflow: ellipsis;
}
/deep/ .tj-tree__item--open {
  position: sticky;
  top: -9px;
  background: #fff;
  z-index: 999;
  width: 226px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
/deep/ .tj-tree__label--strictly {
  width: 88% !important;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
/deep/ .tj-icon-caret-right:before {
  color: #8e959f !important;
  font-size: 16px !important;
}
/deep/ .tj-tree__label--strictly {
  padding-bottom: 6px !important;
  padding-top: 6px !important;
  padding-left: 4px !important;
}
/deep/ .tj-tree__item {
  .tj-is-active {
    background-color: #f5f6f7;
  }
  // height: 100% !important;
}
.checked-box {
  display: flex;
  align-items: center;
  .boxs {
    display: flex;
    align-items: center;
  }
}
/deep/ .tj-icon-caret-right:before {
  // font-size: 18px !important;
}
</style>
